package com.imot.scheduler;

import com.alibaba.fastjson.JSON;
import com.imot.config.SocketManager;
import com.imot.pojo.entity.EmaRecord;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * ClassName: DataPushSchedule
 * Description:
 * date: 2023/11/22 14:15
 *
 * @author imot-jiah.wang
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DataPushSchedule {
    private final List<String> deviceNames = Arrays.asList(
            "机电作动器",
            "动态载荷模拟装置",
            "直线载荷模拟装置",
            "负载控制器",
            "高强度试验台"
    );

    private final List<String> faultLocations = Arrays.asList(
            "阀门",
            "电机",
            "轴承",
            "线性臂",
            "驱动器"
    );
    private final SocketManager socketManager;
    private static final Random random = new Random();
    private long debugDuration = 0; // 调试时长，单位为毫秒
    private long faultInjectionDuration = 0; // 故障注入时长，单位为毫秒
    private int actuationCount = 0; // 作动次数


    @Scheduled(fixedRate = 1000)
    public void datapush() throws IOException {
        long maxDebugDuration = generateRandomDuration(1000, 2000); // 调试时长最大值，单位毫秒
        long maxFaultInjectionDuration = generateRandomDuration(2000, 3000); // 故障注入时长最大值，单位毫秒

        Socket socket = socketManager.getSocket();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8), true);


        EmaRecord emaRecord = new EmaRecord();
        // 温度: -20.00 到 150.00
        emaRecord.setTemperature(randomFloatInRange(60.00f, 70.00f));

        // 速度: -10 到 10
        emaRecord.setSpeed(randomFloatInRange(5f, 6f));

        // 加速度: 0.00 到 5.00
        emaRecord.setAcceleration(randomFloatInRange(2f, 3f));

        // 电源电压: 22.00 到 32.00
        emaRecord.setSupplyVoltage(randomFloatInRange(27.4f, 28.5f));

        // 电机电流: 0.00 到 42.00
        emaRecord.setMotorCurrent(randomFloatInRange(20f, 22f));

        // 电机转速: -5000 到 5000
        emaRecord.setMotorSpeed(randomFloatInRange(2000f, 2200f));

        // 位移: -80.00 到 80.00
        emaRecord.setDisplacement(randomFloatInRange(33f, 37f));

        // 推力: -5000.00 到 5000.00
        emaRecord.setThrust(randomFloatInRange(3000f, 3000f));

        // 电磁扭矩: -100 到 100
        emaRecord.setElecTorque(randomFloatInRange(20f, 30f));

        // 时间: 当前时间
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(dateTimeFormatter);
        emaRecord.setTime(LocalDateTime.now());

        emaRecord.setDeviceName("机电作动器");
        emaRecord.setBalanceStatus("有余度");
        emaRecord.setFaultType("轴承故障");
        emaRecord.setFaultMode("轴承故障模型");
        emaRecord.setTestName("故障模拟试验");
        emaRecord.setCurrentStatus("运行中");
        emaRecord.setTestName("轴承故障模拟试验001");
        emaRecord.setTestCode("GZ001_20231102");
        emaRecord.setErrorLocation("轴承");
        emaRecord.setExceptionLocation("轴承");
        emaRecord.setFaultType("机械类故障");
        emaRecord.setFaultCategory("机械类故障");

        emaRecord.setActuationCount(actuationCount);


        emaRecord.setTestStartTime(String.valueOf(debugDuration / 1000)); // 转换为秒
        emaRecord.setFaultInjectTime(String.valueOf(faultInjectionDuration / 1000)); // 转换为秒

        // 创建一个包含单个 EmaRecord 对象的列表
        List<EmaRecord> records = new ArrayList<>();
        records.add(emaRecord);

// 将整个列表序列化

        Object o = JSON.toJSON(records);

//        log.info("{}",o);
        writer.println(o);

        log.info("{}",o);
        writer.flush();


        if (debugDuration < maxDebugDuration) {
            debugDuration += 1000; // 增加1秒
        } else if (faultInjectionDuration < maxFaultInjectionDuration) {
            faultInjectionDuration += 1000; // 增加1秒
        }

        if (random.nextInt(5) == 0) { // 产生一个 0 到 4 之间的随机数，如果是 0，则增加作动次数
            actuationCount++;
        }
    }

    private long generateRandomDuration(int minSeconds, int maxSeconds) {
        return (long) (random.nextInt(maxSeconds - minSeconds + 1) + minSeconds) * 1000; // 将秒转换为毫秒
    }

    private static float randomFloatInRange(float min, float max) {
        return min + random.nextFloat() * (max - min);
    }
}

